<?php

function formStart($irForm) {
	echo "<form method='".$irForm["Setup"]["Method"]."'>";
}

function formEnd($irForm) {
	echo "<input name='".$irForm["Setup"]["Name"]."' type='submit' value='".$irForm["Setup"]["SubmitLabel"]."'>";
	echo "</form>";
}

function formPutInput($irForm, $isName) {
	foreach ($irForm["Items"] as $lrItem) {
		if($lrItem["Name"] == $isName) {
			if($lrItem["Mandatory"] == 'Y')
				echo "<b>";
			echo $lrItem["Label"].": ";
			if($lrItem["Mandatory"] == 'Y')
				echo "</b>";
			echo "<input type='";
			switch ($lrItem["Type"]) {
				case 'T':
				case 'N':
					echo "text";
					break;
				default:
					echo "text"; // pokud nezname, pujde o standartni input
					break;
			}
			echo "'";
			echo " name='".$lrItem["Name"]."' ";
			echo ">";
		}
	}
}

function generateForm($irForm) {
	formStart($irForm);
	// jednotlive polozky
	foreach ($irForm["Items"] as $lrItem) {
		formPutInput($irForm, $lrItem["Name"]);
		echo "<br />";
	}
	formEnd($irForm);
}

function processForm($lrForm) {
	$lbSent = false;
	$lrResult = array();
	$lrData = array();
	$lrErrors = array();
	//
	if($lrForm["Setup"]["Method"] = "POST") {
		if(isset($_POST[$lrForm["Setup"]["Name"]])) {
			$lbSent = true;
			$lrData = $_POST;
		}
	}
	elseif($lrForm["Setup"]["Method"] = "GET") {
		if(isset($_GET[$lrForm["Setup"]["Name"]])) {
			$lbSent = true;
			$lrData = $_GET;
		}
	}
	//
	if($lbSent) {
		foreach ($lrForm["Items"] as $lrItem) {
			$lsInput = $lrData[$lrItem["Name"]];
			if($lrItem["Mandatory"] == 'Y' && empty($lsInput)) {
				array_push($lrErrors, "Položka ".$lrItem["Label"]." není vyplněna!<br />");
			}
			if($lrItem["Type"] == 'N' && !empty($lsInput) && !is_numeric($lsInput)) {
				array_push($lrErrors, "Položka ".$lrItem["Label"]." musí být číslo!<br />");
			}
			$lrResult[$lrItem["Name"]] = $lsInput;
		}
		$lrResult["_Errors"] = $lrErrors;
	}
	return $lrResult;
}